package com.pp.buvaka;

import com.pp.buvaka.shildt.Parser;
import com.pp.buvaka.shildt.ParserException;
import com.pp.buvaka.table.Field;
import com.pp.buvaka.table.Row;
import com.pp.buvaka.table.Table;
import com.pp.buvaka.table.TableFormatException;
import com.sun.org.apache.xpath.internal.SourceTree;

import java.io.*;
import java.util.ArrayList;



public class MainApp {

    public static void run()  {
        File inputFolder = new File("in");

        File[] list = new File[0];
        try {
            list = Files.getTheListOfFiles(inputFolder);
        } catch (FileNotFoundException e) {
            return;
        }

        if (list.length == 0){
            System.out.println("Empty input dir " + inputFolder.getAbsolutePath());
            return;
        }

        for (int i = 0; i < list.length ; i++) { //all found files
            Table t = new Table();
            System.out.println("Parsing " + list[i].getName());
            ArrayList<String[]> resStr = null; //Collection of expressions by string
            try {
                resStr = Files.parseAndValidateFile(list[i]);
            } catch (TableFormatException e) {
                System.out.println(e);
                continue; //skip corrupted file
            }
            //construct out table
            for (int j = 0; j < resStr.size(); j++) {
                Row r = new Row(resStr.get(j).length);
                r.setFieldsFromStringArray(resStr.get(j));
                t.addRow(r);
            }

            Parser p = new Parser(); p.setTableOfContent(t); //setup the parser
            Table out = new Table();

            //Calculate the table
            for (Row r : t){ //for each row
                Row nextRow = new Row(t.getColumnsCount());
                int index = 0;
                for (Field f : r){ //for each field
                    if(f.getValue().startsWith("=") && f.getValue().length() > 1){ //if expression
                        double res = 0;
                        try {
                            res = p.evaluate(f.getValue().substring(1));
                        } catch (ParserException e) {
                            res = Double.NaN;
                        }
                        nextRow.set(new Field(res), index++);
                    } else { //not an expression - leave as is
                        nextRow.set(new Field(f.getValue()), index++);
                    }
                }
                out.addRow(nextRow);
            }


            //write the result
            PrintStream fs = null;
                try {
                    File fout = new File("out/" + list[i].getName());
                    if (!fout.exists()) { //Create if not exist yet
                        fout.getParentFile().mkdirs();
                        fout.createNewFile();
                    }
                    fs = new PrintStream(fout);
                    for (Row r : out) {
                        fs.println(r.toString());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fs.close();
                    } catch (Exception E) {}
                }
        }
    }

    public static void main(String[] args) throws IOException{
        String cmd;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("\"Run\" to start calculation.");
        System.out.println("\"Exit\" to exit.");

        for(;;) {
            System.out.print("Enter expression: ");
            cmd = br.readLine();
            if(cmd.equalsIgnoreCase("Exit")) break;

            if(cmd.equalsIgnoreCase("Run")) 
                    run();
        }
    }
}


